from pylons import request, response, session, tmpl_context as c, url
from portal.lib.base import BaseController, render
from portal import model
from pylons.controllers.util import abort, redirect
import datetime



def private_page(mako):
    if not check_if_user_is_already_connected():
        session['path_before_login'] = request.path_info
        session.save()
        c.login_error_msg = "Private Page please get authentified"
        return render('/auth/login.mako')
    else:
        return render(mako)

def check_if_user_is_already_connected():
    if 'user' in session:
        return True
    else:
        return False

def create_user_session_variable(user):
    now = datetime.datetime.now()
    
    session['user'] = user.id
    session['last_name'] = user.last_name
    session['chat_time'] = str(now.year)+'-'+str(now.month)+'-'+str(now.day)+' '+str(now.hour)+':'+str(now.minute)+':'+str(now.second)
    session['name'] = user.last_name+' '+user.first_name
    session.save()
    
    
    
    if 'path_before_login' in session:
        path = session['path_before_login']
        del session['path_before_login']
        session.save()
        return redirect(path)
    else:
        return redirect('/start')


def verify_user_login(login, passwd):
    user = model.Session.query(model.User).filter_by(email=login).first()
    
    if user is None:
        c.login_error_msg = "This user does not exist"
        return render('/auth/login.mako')
    if user.password != passwd:
        c.login_error_msg = "Wrong password"
        return render('/auth/login.mako')
    
    create_user_session_variable(user)


def user_logout():
    if 'user' in session:
        del session['user']
        session.save()
